#pragma once
// #ifndef xxx //#if !defined(xxx)
#include <iostream>
#include <sys/types.h>
#include <unistd.h>

// 任务
#define TaskNum 3
typedef void (*task_t)(pid_t); // 函数指针类型

void Print(pid_t pid)
{
    std::cout << "I am Print task, " << pid << " executing me" << std::endl;
}
void DownLoad(pid_t pid)
{
    std::cout << "I am DownLoad task, " << pid << " executing me" << std::endl;
}
void Flush(pid_t pid)
{
    std::cout << "I am Flush task, " << pid << " executing me" << std::endl;
}

task_t tasks[TaskNum]; // 任务函数表
void LoadTask()
{
    srand(time(nullptr) ^ getpid() ^ 17777); // ^ getpid() ^ 17777是为了让种子更随机)
    tasks[0] = Print;
    tasks[1] = DownLoad;
    tasks[2] = Flush;
}

void ExecuteTask(int index, pid_t pid)
{
    if (index < 0 || index > 2)
        return;
    tasks[index](pid); // 函数调用
    
}

int SelectTask() // 轮询旋转
{
    return rand() % TaskNum;
}

// 子进程工作
void Work1()
{
    while (true)
    {
        int taskIndex;
        int n = read(0, &taskIndex, sizeof(taskIndex)); // 读出任务下标
        pid_t pid = getpid();
        if (n == sizeof(int))
        {
            std::cout << "pid is " << pid << " handler task" << std::endl;
            ExecuteTask(taskIndex, pid); // 执行对应任务函数;
            sleep(1);
        }
        else if (n == 0)//管道写端关闭, 直接读到了结尾, 返回0
        {
            std::cout << pid << " wfd quit, read return 0" << std::endl;
            break;
        }
        else //n < 0
        {
            std::cerr << "read fail" << std::endl;
            break;
        }
    }
}